# %% coding=utf-8
import ast
import math
import pandas as pd
from lbs_service import get_travel_time

"""
通过实施派单接口生成新的时间库存
"""

df_artisans = pd.read_csv('data/sample/artisans.csv')
df_orders = pd.read_csv('data/sample/sample_orders.csv')
df_artisans['genes'] = df_artisans['genes'].apply(ast.literal_eval)
city_id = '2'

# 排除关闭时间的订单


def gen_point(se):
    point = str(se['lon']) + "," + str(se['lat'])
    return point


def get_inventory(df_order):
    """
    生成时间库存
    :param df_order:
    :return:
    """
    order_gene = df_order['genes']
    inventory = [0] * (len(order_gene) - 1)
    total_hour = 0
    for i, order in enumerate(order_gene[1:]):
        if order > 0:
            se_order = df_orders.iloc[order]
            # print('df_oder name: ' + str(df_order.name))
            p1 = gen_point(df_artisans.iloc[df_order.name])
            p2 = se_order['point']
            start = str(int(se_order['start_hour']) - 1) + ":00"
            travel_time = get_travel_time(city_id, p1, p2, start)
            if travel_time is not None:
                travel_hour = math.ceil(travel_time/(60 * 30))
                # 锁定路程时间
                travel_start = i - travel_hour if i > travel_hour else 0
                for j in range(i, travel_start, -1):
                    # 检查是否有多余时间供路程锁定
                    # 考虑到样本为已完成的订单，暂不考虑排不下的情况
                    if inventory[j] == 0:
                        total_hour += 1
                        inventory[j] = 1
            inventory[i] = 1
    return inventory, total_hour


df_artisans['inventory'], df_artisans['travel_hour'] = zip(*df_artisans.apply(get_inventory, axis=1))
df_artisans['inventory'] = df_artisans['inventory'].apply(list)
df_artisans.to_csv('validate/disp_inventory.csv')
